﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using System.Data;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 网上考勤
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class AttendanceController : AdminBaseController
    {
        //
        // GET: /Admin/Attendance/

        /// <summary>
        /// 员工BLL
        /// </summary>
        private BLL.HREmpl hrEmplBLL = new BLL.HREmpl();
        /// <summary>
        /// 员工岗位BLL
        /// </summary>
        private BLL.HREmplPosition hrEmplPositionBLL = new BLL.HREmplPosition();
        /// <summary>
        /// 考勤BLL
        /// </summary>
        private BLL.Attendance AttendanceBLL = new BLL.Attendance();
        /// <summary>
        /// 上班时间定义
        /// </summary>
        private BLL.WorkTime WorkTimeBLL = new BLL.WorkTime();
        /// <summary>
        /// 考勤开始日期
        /// </summary>
        private DateTime ATTENDANCE_START_DATE = Common.GenerateUtil.GetConfigValue("attendance_start_date") == "" ? DateTime.Parse("2014-03-12") : DateTime.Parse(Common.GenerateUtil.GetConfigValue("attendance_start_date"));
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 网上考勤统计报表
        /// </summary>
        /// <returns></returns>
        [AuthorityActionFilter("m_AttendanceStatistics", Order = 1)]
        [LogPageActionFilter("网上考勤统计", Order = 2)]
        public ActionResult AttendanceStatistics(int? year = null, int? month = null, string deptno = "")
        {

            if (year == null)
            {
                year = DateTime.Now.Year;
            }
            if (month == null)
            {
                month = DateTime.Now.Month;
            }
            
            ViewData["htmlstr"] = GetData(year.Value.ToString(), month.Value.ToString(), deptno);
            ViewData["mm"] = GetMonth();
            ViewData["yyyy"] = GetYYYY();
            ViewData["dw"] = GetDW();

            ViewData["chooseMonth"] = month;
            ViewData["chooseYear"] = year;
            ViewData["chooseDeptNo"] =deptno;

            return View();
        }

        public ActionResult Save()
        {
            string dw = Fetch.Post("dw_VI");
            string yyyy = Fetch.Post("yyyy_VI");
            string  mm = Fetch.Post("mm_VI");
            if (yyyy == null || yyyy == "")
            {
                yyyy = DateTime.Now.Year.ToString();
            }
            if (mm == null || mm == "")
            {
                mm = DateTime.Now.Month.ToString();
            }
            if (dw == null || dw == "")
            {
                dw = "";
            }
            ViewData["htmlstr"] = GetData(yyyy, mm, dw);
            ViewData["mm"] = GetMonth();
            ViewData["yyyy"] = GetYYYY();
            ViewData["dw"] = GetDW();

            ViewData["chooseMonth"] = mm;
            ViewData["chooseYear"] = yyyy;
            ViewData["chooseDeptNo"] = dw;

            return View("AttendanceStatistics");
        }

        /// <summary>
        /// 获取所有单位
        /// </summary>
        /// <returns>下拉框List</returns>
        public List<SelectListItem> GetDW()
        {
            BLL.HRDept HRDeptBLL = new BLL.HRDept();
            List<Model.HRDept> HRDeptList = HRDeptBLL.GetListBYFIsAgency(Common.GlobalConstant.ENTITYNO, "");
            List<SelectListItem> DWList = new List<SelectListItem>();
            DWList.Add(new SelectListItem() { Value = "", Text = "--选择部门--" });
            foreach (Model.HRDept model in HRDeptList)
            {
                SelectListItem item = new SelectListItem();
                item.Value = model.FDeptNo;
                item.Text = model.FDeptName;
                DWList.Add(item);
            }
            return DWList;
        }

        /// <summary>
        /// 获取所有月份数据
        /// </summary>
        /// <returns>下拉框List</returns>
        public List<SelectListItem> GetMonth()
        {
            List<SelectListItem> MonthList = new List<SelectListItem>();
            for (int i = 1; i < 13; i++)
            {
                SelectListItem item = new SelectListItem();
                
                item.Value = i.ToString();
                item.Text = i + "月";
                MonthList.Add(item);
            }
            return MonthList;
        }

        /// <summary>
        /// 获取现在所有年份数据
        /// </summary>
        /// <returns>下拉框List</returns>
        public List<SelectListItem> GetYYYY()
        {
            List<SelectListItem> YYYYList = new List<SelectListItem>();
            for (int i = DateTime.Now.Year; i > ATTENDANCE_START_DATE.Year-1; i--)
            {
                SelectListItem item = new SelectListItem();
                item.Value = i.ToString();
                item.Text = i + "年";
                YYYYList.Add(item);
            }
            return YYYYList;
        }

        /// <summary>
        /// 获取前台显示Table
        /// </summary>
        /// <param name="year">年份</param>
        /// <param name="month">月份</param>
        /// <param name="deptno">部门编号（空为全部部门）</param>
        /// <returns>STR</returns>
        public string GetData(string year, string month, string deptno)
        {
            int count = 0;
            if (int.Parse(month) < DateTime.Now.Month)
            {
                count = DateTime.DaysInMonth(int.Parse(year), int.Parse(month));
            }
            else
            {
                count = DateTime.Now.Day;
            }

            DateTime beginData = DateTime.Parse(year + "-" + month + "-01");
            DateTime endData = DateTime.Parse(year + "-" + month + "-" + count);


            //获取考勤人员列表
            string entityNo = GlobalConstant.ENTITYNO;
            DataTable emplDT = hrEmplPositionBLL.GetAttendanceMainDeptEmplALL(entityNo, deptno);


            BLL.WorkCalendar WorkCalendarBLL = new BLL.WorkCalendar();
            List<Model.WorkCalendar> WorkCalendarList = WorkCalendarBLL.GetLeaveStatisticsList(beginData.ToString("yyyy-MM-dd"), endData.ToString("yyyy-MM-dd"));

            BLL.HREmplPosition HREmplPositionBLL = new BLL.HREmplPosition();

            DataTable empdt = HREmplPositionBLL.GetLeaveMainDeptEmplALL(Common.GlobalConstant.ENTITYNO);
            BLL.Leave LeaveBLL = new BLL.Leave();
            List<Model.Leave> LeaveList = LeaveBLL.GetLeaveStatisticsList(beginData.ToString("yyyy-MM-dd"), endData.ToString("yyyy-MM-dd"));

            string htmlStr = "<table width='95%' border='1' align='center' cellspacing='0' bordercolordark='#ffffff' bordercolorlight='#000000' cellpadding='4'>";
            htmlStr += @"<tr align='center'>
                        <td  width='80'>部门</td> 
                        <td  width='80' >姓名</td>";
            for (int i = 1; i <= WorkCalendarList.Count; i++)
            {
                htmlStr += " <td>" + i + "</td>";
            }
            if (WorkCalendarList.Count < DateTime.DaysInMonth(int.Parse(year), int.Parse(month)))
            {
                for (int i = WorkCalendarList.Count + 1; i <= DateTime.DaysInMonth(int.Parse(year), int.Parse(month)); i++)
                {
                    htmlStr += " <td>" + i + "</td>";
                }
            }

            htmlStr += "</tr>";

            foreach (DataRow dr in emplDT.Rows)
            {
                string deptNo = dr["FDeptNo"].ToString();
                string deptName = dr["FDeptName"].ToString();
                string emplNo = dr["FEmplNo"].ToString();
                string emplName = dr["FEmpName"].ToString();
                htmlStr += @"<tr align='center'>
                        <td width='80'>" + deptName + @"</td> 
                        <td width='80'>" + emplName + @"</td>";
                for (int i = 0; i < WorkCalendarList.Count; i++)
                {
                    if (WorkCalendarList[i].Fdeftype == "1")
                    {
                        bool isLate = true;//迟到
                        bool isEarly = true;//早退
                        //获取本日最早签到时间

                        Model.WorkTime AttendanceTimeModel = WorkTimeBLL.GetModelByDate(WorkCalendarList[i].FWorkDate.ToShortDateString());
                        string middleTimeStr = WorkCalendarList[i].FWorkDate.Year + "-" + WorkCalendarList[i].FWorkDate.Month + "-" + WorkCalendarList[i].FWorkDate.Day + " " + "12:00";
                        DateTime middleTime = DateTime.Parse(middleTimeStr);//上下午分割时间
                        DateTime amAttendanceTime = DateTime.Parse("00:00");
                        DateTime pmAttendanceTime = DateTime.Parse("00:00");
                        DateTime? firstAttendaceTime = AttendanceBLL.GetFirstAttendanceRecord(WorkCalendarList[i].FWorkDate, entityNo, emplNo);
                        DateTime? lastAttendaceTime = AttendanceBLL.GetLastAttendanceRecord(WorkCalendarList[i].FWorkDate, entityNo, emplNo);

                        if (AttendanceTimeModel != null)
                        {
                            amAttendanceTime = WorkCalendarList[i].FWorkDate.AddMinutes(60 * AttendanceTimeModel.FAMAttendanceTime.Hour + AttendanceTimeModel.FAMAttendanceTime.Minute);
                            pmAttendanceTime = WorkCalendarList[i].FWorkDate.AddMinutes(60 * AttendanceTimeModel.FPMAttendanceTime.Hour + AttendanceTimeModel.FPMAttendanceTime.Minute);

                            if (amAttendanceTime.Hour == 0 && amAttendanceTime.Minute == 0)
                            {
                                //上午上班时间未定义
                                isLate = false;
                            }
                            if (pmAttendanceTime.Hour == 0 && pmAttendanceTime.Minute == 0)
                            {
                                //下午下班时间未定义
                                isEarly = false;
                            }
                            //断点调试代码
                            //if (WorkCalendarList[i].FWorkDate.Day == 19)
                            //{
                            //    if (emplNo == "wangyy")
                            //    {
                            //    }
                            //}

                            if ((WorkCalendarList[i].FWorkDate.Year == DateTime.Now.Year && WorkCalendarList[i].FWorkDate.Month == DateTime.Now.Month
                                && WorkCalendarList[i].FWorkDate.Day == DateTime.Now.Day) || WorkCalendarList[i].FWorkDate <= ATTENDANCE_START_DATE
                        || WorkCalendarList[i].FWorkDate >= DateTime.Now)
                            {
                                //当日考勤数据不统计
                                //考勤开始日期之前的数据都不统计
                                isLate = false;
                                isEarly = false;
                            }
                            else
                            {
                                //与考勤时间比较
                                if (isLate)
                                {
                                    if (firstAttendaceTime.HasValue)
                                    {
                                        if (firstAttendaceTime < middleTime)
                                        {
                                            if (firstAttendaceTime <= amAttendanceTime)
                                            {
                                                isLate = false;
                                            }
                                        }
                                        else
                                        {
                                            firstAttendaceTime = null;
                                        }
                                    }
                                }
                                if (isEarly)
                                {
                                    if (lastAttendaceTime.HasValue)
                                    {
                                        if (lastAttendaceTime >= middleTime)
                                        {
                                            if (lastAttendaceTime >= pmAttendanceTime)
                                            {
                                                isEarly = false;
                                            }
                                        }
                                        else
                                        {
                                            lastAttendaceTime = null;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            //考勤时间未定义
                            isLate = false;
                            isEarly = false;
                        }
                        //人员去向
                        List<Model.Leave> selectLeaveList = (
                            from nm in LeaveList
                            where
                                (nm.FBeginDate.ToShortDateString() == WorkCalendarList[i].FWorkDate.ToShortDateString()
                                || nm.FEndDate.ToShortDateString() == WorkCalendarList[i].FWorkDate.ToShortDateString()
                                || (DateTime.Parse(nm.FEndDate.ToShortDateString()) > DateTime.Parse(WorkCalendarList[i].FWorkDate.ToShortDateString()) && DateTime.Parse(nm.FBeginDate.ToShortDateString()) < DateTime.Parse(WorkCalendarList[i].FWorkDate.ToShortDateString())))
                                && nm.FEmplNo == emplNo
                            select nm).ToList();
                        if (selectLeaveList.Count > 0)
                        {
                            htmlStr += @"<td align='center' style='cursor:hand'>";

                           
                            bool istow = true;
                            foreach (Model.Leave LeaveModel in selectLeaveList)
                            {
                                if (isLate)
                                {
                                    if (amAttendanceTime >= LeaveModel.FBeginDate && amAttendanceTime <= (LeaveModel.FSignOutDate.HasValue ? LeaveModel.FSignOutDate.Value : LeaveModel.FEndDate))
                                    {
                                        //在外出时间之间的
                                        isLate = false;
                                    }
                                }
                                if (isEarly)
                                {
                                    if (pmAttendanceTime >= LeaveModel.FBeginDate && pmAttendanceTime <= (LeaveModel.FSignOutDate.HasValue ? LeaveModel.FSignOutDate.Value : LeaveModel.FEndDate))
                                    {
                                        //在外出时间之间的
                                        isEarly = false;
                                    }
                                }

                                if (LeaveModel.FClass == "2")//1-请假 2-外出
                                {
                                    htmlStr += "<span title='" + LeaveModel.ShowDate + LeaveModel.FLeaveReasonName + "' style='font-size:18px' ><b>*</b></span>";
                                    

                                }
                                else
                                {
                                    
                                    if (LeaveModel.FBeginDate.ToShortDateString() == WorkCalendarList[i].FWorkDate.ToShortDateString())
                                    {
                                        if (LeaveModel.FBeginDate.ToShortDateString() == LeaveModel.FEndDate.ToShortDateString())
                                        {
                                            string ss = LeaveModel.FBeginDate.ToString("HH:mm");
                                            string dd = LeaveModel.FBeginDate.ToString("yyyy-MM-dd");
                                            string ss2 = LeaveModel.FEndDate.ToString("HH:mm");
                                            string dd2 = LeaveModel.FEndDate.ToString("yyyy-MM-dd");
                                            
                                            Model.WorkTime WorkTimeModel = WorkTimeBLL.GetModelByDate(dd);
                                            if (ss2 != WorkTimeModel.FAMEndTimeStr)
                                            {
                                                if (ss != WorkTimeModel.FAMBeginTimeStr)
                                                {
                                                    htmlStr += "<span title='" + LeaveModel.ShowDate + LeaveModel.FLeaveReasonName + "'><b>▲</b></span>";
                                                }
                                                else
                                                {
                                                    htmlStr += "<span title='" + LeaveModel.ShowDate + LeaveModel.FLeaveReasonName + "'><b>◆</b></span>";
                                                }
                                            }
                                            else
                                            {
                                                htmlStr += "<span title='" + LeaveModel.ShowDate + LeaveModel.FLeaveReasonName + "'><b>▲</b></span>";
                                            }
                                        }
                                        else
                                        {
                                            string ss = LeaveModel.FBeginDate.ToString("HH:mm");
                                            string dd = LeaveModel.FBeginDate.ToString("yyyy-MM-dd");
                                            Model.WorkTime WorkTimeModel = WorkTimeBLL.GetModelByDate(dd);
                                            if (ss == WorkTimeModel.FAMBeginTimeStr)
                                            {
                                                htmlStr += "<span title='" + LeaveModel.ShowDate + LeaveModel.FLeaveReasonName + "'><b>◆</b></span>";
                                            }
                                            else
                                            {
                                                htmlStr += "<span title='" + LeaveModel.ShowDate + LeaveModel.FLeaveReasonName + "'><b>▲</b></span>";
                                            }
                                        }
                                    }
                                    else if (LeaveModel.FEndDate.ToShortDateString() == WorkCalendarList[i].FWorkDate.ToShortDateString())
                                    {
                                        string ss = LeaveModel.FEndDate.ToString("HH:mm");
                                        string dd = LeaveModel.FEndDate.ToString("yyyy-MM-dd");
                                        Model.WorkTime WorkTimeModel = WorkTimeBLL.GetModelByDate(dd);
                                        if (ss != WorkTimeModel.FAMEndTimeStr)
                                        {
                                            htmlStr += "<span title='" + LeaveModel.ShowDate + LeaveModel.FLeaveReasonName + "'><b>◆</b></span>";
                                        }
                                        else
                                        {
                                            htmlStr += "<span title='" + LeaveModel.ShowDate + LeaveModel.FLeaveReasonName + "'><b>▲</b></span>";
                                        }

                                    }
                                    else
                                    {
                                        htmlStr += "<span title='" + LeaveModel.ShowDate + LeaveModel.FLeaveReasonName + "'><b>◆</b></span>";
                                    }
                                    istow = false;
                                }
                            }
                            if (istow)
                            {
                                if (isLate)
                                {
                                    htmlStr += "<span title='上午上班迟到,考勤时间为:" + (firstAttendaceTime.HasValue ? firstAttendaceTime.Value.ToString("HH:mm") : "未考勤") + "'><b>△</b></span>";
                                }
                                if (isEarly)
                                {
                                    htmlStr += "<span title='下午下班早退,考勤时间为:" + (lastAttendaceTime.HasValue ? lastAttendaceTime.Value.ToString("HH:mm") : "未考勤") + "'><b>▽</b></span>";
                                }
                                if (!isLate && !isEarly)
                                {

                                    if (WorkCalendarList[i].FWorkDate >= DateTime.Now)
                                    {
                                        htmlStr += "&nbsp;&nbsp;";
                                    }
                                    else
                                    {
                                        htmlStr += " <span title='出勤'>√</span>";
                                    }
                                }
                            }
                            else
                            {
                                if (isLate)
                                {
                                    htmlStr += "<span title='上午上班迟到,考勤时间为:" + (firstAttendaceTime.HasValue ? firstAttendaceTime.Value.ToString("HH:mm") : "未考勤") + "'><b>△</b></span>";
                                }
                                if (isEarly)
                                {
                                    htmlStr += "<span title='下午下班早退,考勤时间为:" + (lastAttendaceTime.HasValue ? lastAttendaceTime.Value.ToString("HH:mm") : "未考勤") + "'><b>▽</b></span>";
                                }
                            }

                            htmlStr += "</td>";
                        }
                        else
                        {
                            htmlStr += "<td align='center' style='cursor:hand'> ";
                            if (isLate)
                                {
                                    htmlStr += "<span title='上午上班迟到,考勤时间为:" + (firstAttendaceTime.HasValue ? firstAttendaceTime.Value.ToString("HH:mm") : "未考勤") + "'><b>△</b></span>";
                                }
                                if (isEarly)
                                {
                                    htmlStr += "<span title='下午下班早退,考勤时间为:" + (lastAttendaceTime.HasValue ? lastAttendaceTime.Value.ToString("HH:mm") : "未考勤") + "'><b>▽</b></span>";
                                }
                                if (!isLate && !isEarly)
                                {

                                    if (WorkCalendarList[i].FWorkDate >= DateTime.Now)
                                    {
                                        htmlStr += "&nbsp;&nbsp;";
                                    }
                                    else
                                    {
                                        htmlStr += " <span title='出勤'>√</span>";
                                    }
                                    
                                }
                                htmlStr += "</td>";
                        }
                    }
                    else
                    {
                        htmlStr += @"<td align='center' style='cursor:hand'>◎</td>";
                    }
                }

                if (WorkCalendarList.Count < DateTime.DaysInMonth(int.Parse(year), int.Parse(month)))
                {
                    DateTime begindatezy = endData.AddDays(1);
                    DateTime endDatazy = DateTime.Parse(year + "-" + month + "-" + DateTime.DaysInMonth(int.Parse(year), int.Parse(month)));

                    List<Model.WorkCalendar> WorkCalendarListzy = WorkCalendarBLL.GetLeaveStatisticsList(begindatezy.ToString("yyyy-MM-dd"), endDatazy.ToString("yyyy-MM-dd"));

                    for (int i = 0; i < WorkCalendarListzy.Count; i++)
                    {
                        if (WorkCalendarListzy[i].Fdeftype != "1")
                        {
                            htmlStr += @"<td align='center' style='cursor:hand'>◎</td>";
                        }
                        else
                        {
                            htmlStr += "<td>&nbsp;&nbsp;</td>";
                        }
                    }
                }

                htmlStr += "</tr>";





                //var tmpEmp = (from c in empdt.AsEnumerable()
                //              where c["FDeptNo"].ToString() == model.FDeptNo
                //              select c);
                //foreach (var q in tmpEmp)
                //{
                   
                //}

            }
            htmlStr += "</table>";
            return htmlStr;
        }

        /// <summary>
        /// 桌面签到签退时间显示
        /// </summary>
        /// <returns></returns>
        public ActionResult DeskAttendance() 
        {
            ViewData["AMAttendanceTime"] = "";
            ViewData["PMAttendanceTime"] = "";
            string entityNo =GlobalConstant.ENTITYNO;
            string loginID = OperateSession.get(GlobalConstant.PARAM_LOGINID);
            BLL.Attendance attendanceBLL = new BLL.Attendance();
            //考勤查询时间 显示                          
            string today = DateTime.Now.Date.ToString();
            string middleTime = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + " " + "12:00";
            //签到显示时间
            DataSet dsAM = attendanceBLL.GetAMAttendanceTimeDS(entityNo, loginID, today);
            if (dsAM.Tables[0].Rows.Count > 0)
            {
                if (DateTime.Parse(middleTime) > DateTime.Parse(DateTime.Parse(dsAM.Tables[0].Rows[0]["FAttendanceTime"].ToString()).ToString("yyyy-MM-dd HH:mm")))
                {
                    ViewData["AMAttendanceTime"] = DateTime.Parse(dsAM.Tables[0].Rows[0]["FAttendanceTime"].ToString()).ToString("HH:mm");
                }
            }
            //签退显示时间
            DataSet dsPM = attendanceBLL.GetPMAttendanceTimeDS(entityNo, loginID, today);

            if (dsPM.Tables[0].Rows.Count > 0)
            {
                if (DateTime.Parse(middleTime) <= DateTime.Parse(DateTime.Parse(dsPM.Tables[0].Rows[0]["FAttendanceTime"].ToString()).ToString("yyyy-MM-dd HH:mm")))
                {
                    ViewData["PMAttendanceTime"] = DateTime.Parse(dsPM.Tables[0].Rows[0]["FAttendanceTime"].ToString()).ToString("HH:mm");
                }
            }
 

            return View();
        }

    }
}
